import './ChatPage.css'
import http from '@/utils/axios';

import { memo, useState, useEffect } from "react";
import useStore from '@/store';
import { useParams, useNavigate } from 'react-router-dom';

import ChatTopBar from '@/components/ChatTopBar';
import DialoguePanel from '@/components/DialoguePanel/DialoguePanel';
import ChatInputPanel from "@/components/ChatInputPanel";
import MenuOutlinedIcon from '@mui/icons-material/MenuOutlined';

const ChatPage = memo(() => {
    // console.log("ChatPage");
    const { uuid } = useParams();
    const navigate = useNavigate();
    const currentDialogueUUID = useStore(state => state.currentDialogueUUID);
    const setCurrentDialogueUUID = useStore(state => state.setCurrentDialogueUUID);

    const dialogue = useStore(state => state.dialogues?.[uuid]);
    const addDialogue = useStore(state => state.addDialogue);
    const setDialogueModel = useStore(state => state.setDialogueModel);
    const setDialogue = useStore(state => state.setDialogue);

    const handleOpenAILLMAPIFetch = useStore(state => state.handleOpenAILLMAPIFetch);
    const deleteDialogueHistoryTag = useStore(state => state.deleteDialogueHistoryTag);

    const isLoading = !dialogue;
    const [error, setError] = useState(null);

    const handleFetchDialogue = async (uuid) => {
        try {
            const response = await http.get(`/dialogue/${uuid}`);
            addDialogue(uuid, response.data);
            // console.log('addDialogue');
        } catch (error) {
            setError(error.message);
            if (error.response) {
                // 访问状态码
                const statusCode = error.response.status;
                // console.log(`Error status code: ${statusCode}`);
                if (statusCode === 404) deleteDialogueHistoryTag(uuid);
            }
            navigate("/");
        }
    }

    useEffect(() => {
        // console.log('uuuid changed');
        if (error) setError(null);
        if (currentDialogueUUID != uuid) setCurrentDialogueUUID(uuid);
        if (isLoading) handleFetchDialogue(uuid);
    }, [uuid,])

    const handleOnSelectedModel = (model) => {
        setDialogueModel(uuid, model);
    }

    const hendleEnter = async (prompt, setPrompt) => {
        const new_dialogue_content_json = [...dialogue.dialogue_content_json, { 'role': 'user', 'content': prompt }]
        setDialogue(uuid, new_dialogue_content_json)
        setPrompt('');
        await http.put(`/dialogue/${uuid}`, { current_model: dialogue.current_model, dialogue_content_json: new_dialogue_content_json });
        handleOpenAILLMAPIFetch(uuid, dialogue.current_model, new_dialogue_content_json);
    }

    const sidebarVisibility = useStore(state => state.sidebarVisibility);
    const toggleSidebarVisibility = useStore(state => state.toggleSidebarVisibility);


    if (isLoading) {
        return (<div className='chat-top-bar'>
            <div className='chat-top-bar-content' >
                <button className='button-bar-button' onClick={toggleSidebarVisibility} style={{ display: sidebarVisibility ? 'none' : '' }} >
                    <MenuOutlinedIcon />
                </button>
            </div>
        </div>)
    }

    if (error) {
        navigate('/');
    }

    return (
        // chatarea
        <div className='chat-page'>
            <div className='chat-page-content'>
                <div className='chat-page-top-bar' ><ChatTopBar selectedModel={dialogue.current_model} onSelectedModel={handleOnSelectedModel} uuid={uuid} /> </div>
                <DialoguePanel uuid={uuid} dialogue={dialogue} />
            </div>
            <ChatInputPanel onEnter={hendleEnter} disabled={isLoading} />
        </div>
    )
});

export default ChatPage;